package models

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"os"
	"strconv"
	"time"

	"github.com/beego/beego/v2/client/orm"
)

// PaymentChannel 支付渠道模型
type PaymentChannel struct {
	BaseModel
	Name        string `orm:"size(50)" json:"name"`
	Code        string `orm:"size(20);unique" json:"code"` // 渠道代码：alipay, wechat, etc.
	Type        string `orm:"size(20)" json:"type"`        // 支付类型：online, offline, etc.
	Icon        string `orm:"size(255)" json:"icon"`
	Description string `orm:"size(255)" json:"description"`
	Config      string `orm:"type(text)" json:"config"`     // 配置信息，JSON格式存储
	Status      int8   `orm:"default(1)" json:"status"`     // 1:启用, 0:禁用
	SortOrder   int    `orm:"default(0)" json:"sort_order"` // 排序
	IsDefault   int8   `orm:"default(0)" json:"is_default"` // 是否默认，1:是，0:否
}

// PaymentChannelLog 支付渠道操作日志
type PaymentChannelLog struct {
	BaseModel
	ChannelId  int64  `orm:"index" json:"channel_id"`    // 关联的支付渠道ID
	Action     string `orm:"size(50)" json:"action"`     // 操作类型：status_change, config_update, etc.
	OldValue   string `orm:"size(255)" json:"old_value"` // 操作前的值
	NewValue   string `orm:"size(255)" json:"new_value"` // 操作后的值
	OperatorId int64  `orm:"index" json:"operator_id"`   // 操作人ID
	Remark     string `orm:"size(255)" json:"remark"`    // 备注
}

// PaymentChannelStats 支付渠道统计
type PaymentChannelStats struct {
	ChannelId         int64   `json:"channel_id"`
	ChannelName       string  `json:"channel_name"`
	TotalAmount       float64 `json:"total_amount"`
	TotalCount        int64   `json:"total_count"`
	SuccessCount      int64   `json:"success_count"`
	FailedCount       int64   `json:"failed_count"`
	TotalFee          float64 `json:"total_fee"`
	AverageAmount     float64 `json:"average_amount"`
	SuccessRate       float64 `json:"success_rate"`
	LastTransactionAt int64   `json:"last_transaction_at"`
}

// PaymentChannelHealth 支付渠道健康状态
type PaymentChannelHealth struct {
	ChannelId           int64   `json:"channel_id"`
	ChannelName         string  `json:"channel_name"`
	Status              string  `json:"status"`                // healthy, warning, critical
	ResponseTime        int64   `json:"response_time"`         // 毫秒
	SuccessRate         float64 `json:"success_rate"`          // 近期成功率
	LastCheckTime       int64   `json:"last_check_time"`       // 最后检查时间
	ConsecutiveFailures int     `json:"consecutive_failures"`  // 连续失败次数
	AverageResponseTime int64   `json:"average_response_time"` // 平均响应时间
	AvailabilityPercent float64 `json:"availability_percent"`  // 可用性百分比
}

// TableName 设置表名
func (p *PaymentChannel) TableName() string {
	return "ss_payment_channel"
}

// TableName 设置日志表名
func (p *PaymentChannelLog) TableName() string {
	return "ss_payment_channel_log"
}

// ValidateConfig 验证支付渠道配置
func (p *PaymentChannel) ValidateConfig() error {
	var config map[string]interface{}
	if err := json.Unmarshal([]byte(p.Config), &config); err != nil {
		return fmt.Errorf("配置格式错误: %v", err)
	}

	// 根据不同类型验证必填字段
	switch p.Type {
	case "alipay":
		if _, ok := config["app_id"]; !ok {
			return errors.New("支付宝配置缺少app_id")
		}
		if _, ok := config["private_key"]; !ok {
			return errors.New("支付宝配置缺少private_key")
		}
	case "wechat":
		if _, ok := config["app_id"]; !ok {
			return errors.New("微信支付配置缺少app_id")
		}
		if _, ok := config["mch_id"]; !ok {
			return errors.New("微信支付配置缺少mch_id")
		}
	case "unionpay":
		if _, ok := config["merchant_id"]; !ok {
			return errors.New("银联支付配置缺少merchant_id")
		}
		if _, ok := config["cert_path"]; !ok {
			return errors.New("银联支付配置缺少cert_path")
		}
	case "balance":
		// 余额支付不需要特殊配置
	}
	return nil
}

// EncryptConfig 加密配置信息
func (p *PaymentChannel) EncryptConfig() error {
	if p.Config == "" {
		return nil
	}

	// 获取加密密钥
	key := []byte(os.Getenv("PAYMENT_CONFIG_KEY"))
	if len(key) == 0 {
		// 如果没有设置密钥，使用默认密钥（不推荐用于生产环境）
		key = []byte("default_payment_key_32_bytes_long_for_aes")
	}

	// 创建加密器
	block, err := aes.NewCipher(key)
	if err != nil {
		return err
	}

	// 加密配置
	encrypted, err := encryptAES([]byte(p.Config), block)
	if err != nil {
		return err
	}

	p.Config = base64.StdEncoding.EncodeToString(encrypted)
	return nil
}

// DecryptConfig 解密配置信息
func (p *PaymentChannel) DecryptConfig() error {
	if p.Config == "" {
		return nil
	}

	// 获取加密密钥
	key := []byte(os.Getenv("PAYMENT_CONFIG_KEY"))
	if len(key) == 0 {
		// 如果没有设置密钥，使用默认密钥（不推荐用于生产环境）
		key = []byte("default_payment_key_32_bytes_long_for_aes")
	}

	// 创建加密器
	block, err := aes.NewCipher(key)
	if err != nil {
		return err
	}

	// 解码Base64
	encrypted, err := base64.StdEncoding.DecodeString(p.Config)
	if err != nil {
		return err
	}

	// 解密配置
	decrypted, err := decryptAES(encrypted, block)
	if err != nil {
		return err
	}

	p.Config = string(decrypted)
	return nil
}

// UpdateStatus 更新状态并记录日志
func (p *PaymentChannel) UpdateStatus(status int8, operatorId int64) error {
	o := orm.NewOrm()
	tx, err := o.Begin()
	if err != nil {
		return err
	}
	defer tx.Rollback()

	// 更新状态
	oldStatus := p.Status
	p.Status = status
	p.UpdatedAt = time.Now().Unix()
	if _, err := tx.Update(p, "Status", "UpdatedAt"); err != nil {
		return err
	}

	// 记录状态变更
	log := &PaymentChannelLog{
		ChannelId:  p.Id,
		Action:     "status_change",
		OldValue:   strconv.FormatInt(int64(oldStatus), 10),
		NewValue:   strconv.FormatInt(int64(status), 10),
		OperatorId: operatorId,
	}
	if _, err := tx.Insert(log); err != nil {
		return err
	}

	return tx.Commit()
}

// TestConnection 测试支付渠道连接
func (p *PaymentChannel) TestConnection() error {
	// 解密配置
	if err := p.DecryptConfig(); err != nil {
		return err
	}

	switch p.Type {
	case "alipay":
		return p.testAlipayConnection()
	case "wechat":
		return p.testWechatConnection()
	case "unionpay":
		return p.testUnionpayConnection()
	default:
		return fmt.Errorf("不支持的支付类型: %s", p.Type)
	}
}

// 测试支付宝连接
func (p *PaymentChannel) testAlipayConnection() error {
	var config map[string]interface{}
	if err := json.Unmarshal([]byte(p.Config), &config); err != nil {
		return err
	}

	// 这里应该实现实际的支付宝API测试
	// 由于没有实际的支付宝SDK，这里只是模拟测试
	appId, ok := config["app_id"].(string)
	if !ok || appId == "" {
		return errors.New("无效的app_id")
	}

	return nil
}

// 测试微信支付连接
func (p *PaymentChannel) testWechatConnection() error {
	var config map[string]interface{}
	if err := json.Unmarshal([]byte(p.Config), &config); err != nil {
		return err
	}

	// 这里应该实现实际的微信支付API测试
	// 由于没有实际的微信支付SDK，这里只是模拟测试
	appId, ok := config["app_id"].(string)
	if !ok || appId == "" {
		return errors.New("无效的app_id")
	}

	mchId, ok := config["mch_id"].(string)
	if !ok || mchId == "" {
		return errors.New("无效的mch_id")
	}

	return nil
}

// 测试银联支付连接
func (p *PaymentChannel) testUnionpayConnection() error {
	var config map[string]interface{}
	if err := json.Unmarshal([]byte(p.Config), &config); err != nil {
		return err
	}

	// 这里应该实现实际的银联支付API测试
	// 由于没有实际的银联支付SDK，这里只是模拟测试
	merchantId, ok := config["merchant_id"].(string)
	if !ok || merchantId == "" {
		return errors.New("无效的merchant_id")
	}

	return nil
}

// 加密AES数据
func encryptAES(data []byte, block cipher.Block) ([]byte, error) {
	// 创建GCM模式
	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}

	// 创建随机数
	nonce := make([]byte, gcm.NonceSize())
	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
		return nil, err
	}

	// 加密数据
	ciphertext := gcm.Seal(nonce, nonce, data, nil)
	return ciphertext, nil
}

// 解密AES数据
func decryptAES(data []byte, block cipher.Block) ([]byte, error) {
	// 创建GCM模式
	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}

	// 检查数据长度
	if len(data) < gcm.NonceSize() {
		return nil, errors.New("密文太短")
	}

	// 提取随机数
	nonce := data[:gcm.NonceSize()]
	ciphertext := data[gcm.NonceSize():]

	// 解密数据
	plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
	if err != nil {
		return nil, err
	}

	return plaintext, nil
}

// GetPaymentChannelById 根据ID获取支付渠道信息
func GetPaymentChannelById(id int64) (*PaymentChannel, error) {
	channel := &PaymentChannel{BaseModel: BaseModel{Id: id}}
	o := orm.NewOrm()
	err := o.Read(channel)
	if err == nil {
		// 尝试解密配置
		channel.DecryptConfig()
	}
	return channel, err
}

// GetPaymentChannelByCode 根据代码获取支付渠道信息
func GetPaymentChannelByCode(code string) (*PaymentChannel, error) {
	channel := &PaymentChannel{Code: code}
	o := orm.NewOrm()
	err := o.Read(channel, "Code")
	if err == nil {
		// 尝试解密配置
		channel.DecryptConfig()
	}
	return channel, err
}

// GetPaymentChannelList 获取支付渠道列表
func GetPaymentChannelList(page, pageSize int, filters map[string]interface{}) ([]*PaymentChannel, int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(PaymentChannel))

	// 应用过滤条件
	if name, ok := filters["name"].(string); ok && name != "" {
		qs = qs.Filter("name__contains", name)
	}

	if code, ok := filters["code"].(string); ok && code != "" {
		qs = qs.Filter("code", code)
	}

	if channelType, ok := filters["type"].(string); ok && channelType != "" {
		qs = qs.Filter("type", channelType)
	}

	if status, ok := filters["status"].(int8); ok {
		qs = qs.Filter("status", status)
	}

	// 加盟商过滤
	if franchiseId, ok := filters["franchise_id"].(int64); ok && franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	// 排除已删除的记录
	qs = qs.Filter("is_deleted", 0)

	// 获取总数
	total, _ := qs.Count()

	// 分页查询
	var channels []*PaymentChannel
	_, err := qs.OrderBy("sort_order", "-id").Limit(pageSize, (page-1)*pageSize).All(&channels)

	// 解密配置
	for _, channel := range channels {
		channel.DecryptConfig()
	}

	return channels, total, err
}

// CreatePaymentChannel 创建支付渠道
func CreatePaymentChannel(channel *PaymentChannel) (int64, error) {
	// 验证配置
	if err := channel.ValidateConfig(); err != nil {
		return 0, err
	}

	// 加密配置
	if err := channel.EncryptConfig(); err != nil {
		return 0, err
	}

	o := orm.NewOrm()
	id, err := o.Insert(channel)
	return id, err
}

// UpdatePaymentChannel 更新支付渠道信息
func UpdatePaymentChannel(channel *PaymentChannel, fields ...string) error {
	// 如果更新了配置，需要验证和加密
	needValidate := false
	needEncrypt := false
	for _, field := range fields {
		if field == "Config" {
			needValidate = true
			needEncrypt = true
		}
	}

	if needValidate {
		if err := channel.ValidateConfig(); err != nil {
			return err
		}
	}

	if needEncrypt {
		if err := channel.EncryptConfig(); err != nil {
			return err
		}
	}

	o := orm.NewOrm()
	_, err := o.Update(channel, fields...)
	return err
}

// DeletePaymentChannel 删除支付渠道（软删除）
func DeletePaymentChannel(id int64) error {
	o := orm.NewOrm()
	channel := &PaymentChannel{BaseModel: BaseModel{Id: id}}
	if err := o.Read(channel); err != nil {
		return err
	}

	channel.IsDeleted = 1
	_, err := o.Update(channel, "IsDeleted")
	return err
}

// GetActivePaymentChannels 获取所有激活的支付渠道
func GetActivePaymentChannels() ([]*PaymentChannel, error) {
	o := orm.NewOrm()
	var channels []*PaymentChannel
	_, err := o.QueryTable(new(PaymentChannel)).Filter("status", 1).Filter("is_deleted", 0).OrderBy("sort_order").All(&channels)

	// 解密配置
	for _, channel := range channels {
		channel.DecryptConfig()
	}

	return channels, err
}

// SetDefaultPaymentChannel 设置默认支付渠道
func SetDefaultPaymentChannel(id int64) error {
	o := orm.NewOrm()

	// 先将所有渠道设为非默认
	_, err := o.QueryTable(new(PaymentChannel)).Update(orm.Params{
		"is_default": 0,
		"updated_at": time.Now().Unix(),
	})
	if err != nil {
		return err
	}

	// 设置指定渠道为默认
	channel := &PaymentChannel{BaseModel: BaseModel{Id: id}}
	if err := o.Read(channel); err != nil {
		return err
	}

	channel.IsDefault = 1
	_, err = o.Update(channel, "IsDefault", "UpdatedAt")
	return err
}

// GetPaymentChannelLogs 获取支付渠道操作日志
func GetPaymentChannelLogs(channelId int64, page, pageSize int) ([]*PaymentChannelLog, int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(PaymentChannelLog))

	// 按渠道ID过滤
	if channelId > 0 {
		qs = qs.Filter("channel_id", channelId)
	}

	// 获取总数
	total, _ := qs.Count()

	// 分页查询
	var logs []*PaymentChannelLog
	_, err := qs.OrderBy("-created_at").Limit(pageSize, (page-1)*pageSize).All(&logs)

	return logs, total, err
}

// BatchUpdatePaymentChannelStatus 批量更新支付渠道状态
func BatchUpdatePaymentChannelStatus(ids []int64, status int8, operatorId int64) error {
	o := orm.NewOrm()
	tx, err := o.Begin()
	if err != nil {
		return err
	}
	defer tx.Rollback()

	// 更新状态
	_, err = tx.QueryTable(new(PaymentChannel)).Filter("id__in", ids).Update(orm.Params{
		"status":     status,
		"updated_at": time.Now().Unix(),
	})
	if err != nil {
		return err
	}

	// 记录日志
	for _, id := range ids {
		log := &PaymentChannelLog{
			ChannelId:  id,
			Action:     "status_change",
			OldValue:   "unknown", // 由于是批量操作，无法获取旧值
			NewValue:   strconv.FormatInt(int64(status), 10),
			OperatorId: operatorId,
		}
		if _, err := tx.Insert(log); err != nil {
			return err
		}
	}

	return tx.Commit()
}

// BatchDeletePaymentChannels 批量删除支付渠道
func BatchDeletePaymentChannels(ids []int64) error {
	o := orm.NewOrm()
	tx, err := o.Begin()
	if err != nil {
		return err
	}
	defer tx.Rollback()

	// 软删除
	_, err = tx.QueryTable(new(PaymentChannel)).Filter("id__in", ids).Update(orm.Params{
		"is_deleted": 1,
		"updated_at": time.Now().Unix(),
	})
	if err != nil {
		return err
	}

	return tx.Commit()
}

// GetPaymentChannelByType 根据类型获取支付渠道
func GetPaymentChannelByType(channelType string) ([]*PaymentChannel, error) {
	o := orm.NewOrm()
	var channels []*PaymentChannel
	_, err := o.QueryTable(new(PaymentChannel)).Filter("type", channelType).Filter("status", 1).Filter("is_deleted", 0).OrderBy("sort_order").All(&channels)

	// 解密配置
	for _, channel := range channels {
		channel.DecryptConfig()
	}

	return channels, err
}

// GetDefaultPaymentChannel 获取默认支付渠道
func GetDefaultPaymentChannel() (*PaymentChannel, error) {
	o := orm.NewOrm()
	channel := &PaymentChannel{}
	err := o.QueryTable(new(PaymentChannel)).Filter("is_default", 1).Filter("status", 1).Filter("is_deleted", 0).One(channel)
	if err != nil {
		return nil, err
	}

	// 解密配置
	channel.DecryptConfig()

	return channel, nil
}

// GetPaymentChannelStatistics 获取支付渠道统计信息
func GetPaymentChannelStatistics() (map[string]interface{}, error) {
	o := orm.NewOrm()

	// 获取总数
	total, err := o.QueryTable(new(PaymentChannel)).Filter("is_deleted", 0).Count()
	if err != nil {
		return nil, err
	}

	// 获取启用数量
	enabled, err := o.QueryTable(new(PaymentChannel)).Filter("status", 1).Filter("is_deleted", 0).Count()
	if err != nil {
		return nil, err
	}

	// 获取禁用数量
	disabled, err := o.QueryTable(new(PaymentChannel)).Filter("status", 0).Filter("is_deleted", 0).Count()
	if err != nil {
		return nil, err
	}

	// 按类型统计
	var typeStats []orm.Params
	_, err = o.Raw("SELECT type, COUNT(*) as count FROM ss_payment_channel WHERE is_deleted = 0 GROUP BY type").Values(&typeStats)
	if err != nil {
		return nil, err
	}

	result := map[string]interface{}{
		"total":     total,
		"enabled":   enabled,
		"disabled":  disabled,
		"typeStats": typeStats,
	}

	return result, nil
}

// AutoSwitchChannel 自动切换支付渠道
func AutoSwitchChannel(amount float64, currency string) (*PaymentChannel, error) {
	o := orm.NewOrm()
	var channels []*PaymentChannel

	// 获取所有可用的支付渠道
	_, err := o.QueryTable(new(PaymentChannel)).
		Filter("status", 1).
		Filter("is_deleted", 0).
		OrderBy("sort_order").
		All(&channels)

	if err != nil {
		return nil, err
	}

	// 遍历渠道，检查是否满足条件
	for _, channel := range channels {
		// 解密配置
		if err := channel.DecryptConfig(); err != nil {
			continue
		}

		var config map[string]interface{}
		if err := json.Unmarshal([]byte(channel.Config), &config); err != nil {
			continue
		}

		// 检查金额限制
		if minAmount, ok := config["min_amount"].(float64); ok {
			if amount < minAmount {
				continue
			}
		}
		if maxAmount, ok := config["max_amount"].(float64); ok {
			if amount > maxAmount {
				continue
			}
		}

		// 检查货币支持
		if supportedCurrencies, ok := config["supported_currencies"].([]interface{}); ok {
			currencySupported := false
			for _, c := range supportedCurrencies {
				if c.(string) == currency {
					currencySupported = true
					break
				}
			}
			if !currencySupported {
				continue
			}
		}

		// 检查渠道状态
		if err := channel.TestConnection(); err != nil {
			continue
		}

		return channel, nil
	}

	return nil, errors.New("没有可用的支付渠道")
}

// GetChannelStats 获取渠道统计数据
func GetChannelStats(channelId int64, startTime, endTime int64) (*PaymentChannelStats, error) {
	o := orm.NewOrm()

	// 获取渠道信息
	channel := &PaymentChannel{BaseModel: BaseModel{Id: channelId}}
	if err := o.Read(channel); err != nil {
		return nil, err
	}

	// 构建统计查询
	stats := &PaymentChannelStats{
		ChannelId:   channelId,
		ChannelName: channel.Name,
	}

	// 查询交易总额和笔数
	var result []orm.Params
	_, err := o.Raw(`
		SELECT 
			COUNT(*) as total_count,
			SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) as success_count,
			SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed_count,
			SUM(amount) as total_amount,
			SUM(fee) as total_fee,
			MAX(created_at) as last_transaction_at
		FROM ss_payment_transaction 
		WHERE channel_id = ? AND created_at BETWEEN ? AND ?
	`, channelId, startTime, endTime).Values(&result)

	if err != nil {
		return nil, err
	}

	if len(result) > 0 {
		stats.TotalCount = result[0]["total_count"].(int64)
		stats.SuccessCount = result[0]["success_count"].(int64)
		stats.FailedCount = result[0]["failed_count"].(int64)
		stats.TotalAmount = result[0]["total_amount"].(float64)
		stats.TotalFee = result[0]["total_fee"].(float64)
		stats.LastTransactionAt = result[0]["last_transaction_at"].(int64)

		// 计算平均值和成功率
		if stats.TotalCount > 0 {
			stats.AverageAmount = stats.TotalAmount / float64(stats.TotalCount)
			stats.SuccessRate = float64(stats.SuccessCount) / float64(stats.TotalCount) * 100
		}
	}

	return stats, nil
}

// GetAllChannelsStats 获取所有渠道统计数据
func GetAllChannelsStats(startTime, endTime int64) ([]*PaymentChannelStats, error) {
	o := orm.NewOrm()
	var channels []*PaymentChannel
	_, err := o.QueryTable(new(PaymentChannel)).
		Filter("is_deleted", 0).
		All(&channels)

	if err != nil {
		return nil, err
	}

	var stats []*PaymentChannelStats
	for _, channel := range channels {
		stat, err := GetChannelStats(channel.Id, startTime, endTime)
		if err != nil {
			continue
		}
		stats = append(stats, stat)
	}

	return stats, nil
}

// CheckChannelHealth 检查支付渠道健康状态
func CheckChannelHealth(channelId int64) (*PaymentChannelHealth, error) {
	o := orm.NewOrm()

	// 获取渠道信息
	channel := &PaymentChannel{BaseModel: BaseModel{Id: channelId}}
	if err := o.Read(channel); err != nil {
		return nil, err
	}

	health := &PaymentChannelHealth{
		ChannelId:     channelId,
		ChannelName:   channel.Name,
		LastCheckTime: time.Now().Unix(),
	}

	// 开始计时
	startTime := time.Now()

	// 测试连接
	err := channel.TestConnection()

	// 计算响应时间（毫秒）
	health.ResponseTime = time.Since(startTime).Milliseconds()

	if err != nil {
		health.Status = "critical"
		// 更新连续失败次数
		incrementChannelFailureCount(channelId)
	} else {
		health.Status = "healthy"
		// 重置连续失败次数
		resetChannelFailureCount(channelId)
	}

	// 获取近期成功率
	health.SuccessRate = getChannelRecentSuccessRate(channelId)

	// 获取连续失败次数
	health.ConsecutiveFailures = getChannelFailureCount(channelId)

	// 获取平均响应时间
	health.AverageResponseTime = getChannelAverageResponseTime(channelId)

	// 计算可用性
	health.AvailabilityPercent = calculateChannelAvailability(channelId)

	// 根据综合指标确定最终状态
	if health.SuccessRate < 85 || health.ConsecutiveFailures > 3 || health.AverageResponseTime > 5000 {
		health.Status = "warning"
	}
	if health.SuccessRate < 70 || health.ConsecutiveFailures > 5 || health.AverageResponseTime > 10000 {
		health.Status = "critical"
	}

	// 保存健康记录
	saveChannelHealthRecord(channelId, health)

	return health, nil
}

// 获取渠道近期成功率
func getChannelRecentSuccessRate(channelId int64) float64 {
	o := orm.NewOrm()
	// 获取最近24小时的交易数据
	endTime := time.Now().Unix()
	startTime := endTime - 86400 // 24小时前

	var result []orm.Params
	_, err := o.Raw(`
		SELECT 
			COUNT(*) as total,
			SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) as success
		FROM ss_payment_transaction 
		WHERE channel_id = ? AND created_at BETWEEN ? AND ?
	`, channelId, startTime, endTime).Values(&result)

	if err != nil || len(result) == 0 {
		return 100 // 默认100%，如果没有交易数据
	}

	total, _ := strconv.ParseInt(result[0]["total"].(string), 10, 64)
	success, _ := strconv.ParseInt(result[0]["success"].(string), 10, 64)

	if total == 0 {
		return 100
	}

	return float64(success) / float64(total) * 100
}

// 增加渠道连续失败次数
func incrementChannelFailureCount(channelId int64) {
	key := fmt.Sprintf("channel_failure_count_%d", channelId)
	// 实际实现应该使用Redis或其他缓存服务
	// 这里仅作为示例，使用文件存储
	countStr := readFromCacheFile(key)
	count, _ := strconv.Atoi(countStr)
	count++
	writeToCacheFile(key, strconv.Itoa(count))
}

// 重置渠道连续失败次数
func resetChannelFailureCount(channelId int64) {
	key := fmt.Sprintf("channel_failure_count_%d", channelId)
	// 实际实现应该使用Redis或其他缓存服务
	writeToCacheFile(key, "0")
}

// 获取渠道连续失败次数
func getChannelFailureCount(channelId int64) int {
	key := fmt.Sprintf("channel_failure_count_%d", channelId)
	// 实际实现应该使用Redis或其他缓存服务
	countStr := readFromCacheFile(key)
	count, _ := strconv.Atoi(countStr)
	return count
}

// 获取渠道平均响应时间
func getChannelAverageResponseTime(channelId int64) int64 {
	// 这里应该从监控系统获取数据
	// 示例实现返回固定值
	return 200 // 200ms
}

// 计算渠道可用性
func calculateChannelAvailability(channelId int64) float64 {
	// 从监控系统获取过去30天的可用性数据
	// 示例实现返回固定值
	return 99.9 // 99.9%
}

// 保存渠道健康记录
func saveChannelHealthRecord(channelId int64, health *PaymentChannelHealth) {
	// 实际应该保存到数据库中，以便生成历史趋势图表
	// 这里仅作为示例
}

// 从缓存文件读取数据
func readFromCacheFile(key string) string {
	// 实际应该使用Redis或其他缓存服务
	// 这里仅作为示例
	cacheDir := "cache"
	os.MkdirAll(cacheDir, 0755)

	data, err := os.ReadFile(cacheDir + "/" + key)
	if err != nil {
		return "0"
	}
	return string(data)
}

// 写入数据到缓存文件
func writeToCacheFile(key, value string) {
	// 实际应该使用Redis或其他缓存服务
	// 这里仅作为示例
	cacheDir := "cache"
	os.MkdirAll(cacheDir, 0755)

	os.WriteFile(cacheDir+"/"+key, []byte(value), 0644)
}

// CheckAllChannelsHealth 检查所有支付渠道的健康状态
func CheckAllChannelsHealth() ([]*PaymentChannelHealth, error) {
	o := orm.NewOrm()
	var channels []*PaymentChannel
	_, err := o.QueryTable(new(PaymentChannel)).
		Filter("status", 1).
		Filter("is_deleted", 0).
		All(&channels)

	if err != nil {
		return nil, err
	}

	var results []*PaymentChannelHealth
	for _, channel := range channels {
		health, err := CheckChannelHealth(channel.Id)
		if err != nil {
			continue
		}
		results = append(results, health)
	}

	return results, nil
}
